package com.behelpful.demo.gateway.handler;

import com.behelpful.common.core.result.R;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关异常通用处理器，只作用在webflux 环境下 , 优先级低于 {@link ResponseStatusExceptionHandler} 执行
 *
 * @author Alay
 * @date 2021-09-25 11:08
 */
@Slf4j
@Order(-1)
@Component
public class WebFluxGlobeExceptionHandler implements ErrorWebExceptionHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable exception) {

        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(exception);
        }

        // 头信息设置
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        if (exception instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) exception).getStatus());
        }

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                // 返回数据封装
                R errResult = R.failed(exception.getMessage());
                log.warn("写入响应信息异常信息:{} , cause：{}, 异常类: {}", exception.getMessage(),exception.getCause(),exception.getClass().getName());
                return bufferFactory.wrap(objectMapper.writeValueAsBytes(errResult));
            } catch (JsonProcessingException e) {
                log.warn("写入响应信息异常信息:{} , cause：{}, 异常类: {}", exception.getMessage(),exception.getCause(),exception.getClass().getName());
                return bufferFactory.wrap(new byte[0]);
            }
        }));
    }
}
